package com.alex.service;

import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.TermQuery;

import com.alex.service.Search_Plans.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.alex.utils.MyUtils.zsout;


@Component
@SuppressWarnings("ALL")
@Slf4j
public class SecondAnalysisService {

    public static void main(String[] args) {
        String string = "CANCER[TI]";
        Pattern pattern = Pattern.compile(".*\\[([a-zA-Z]+)\\]");
        Matcher matcher = pattern.matcher(string);
        if (matcher.find()) {
            String xian_ding = matcher.group(1);
            String search_world = string.replace("[" + xian_ding + "]", "").trim();
            System.out.println("规范前的限定词___" + search_world + " [" + xian_ding + "]");
        }

    }


    /**
     * 单个检索词开始
     *
     * @param expressStr
     * @return
     */
    public Query getQuery(String freeWord, boolean printLog) {
        //初步处理
        freeWord = freeWord.toLowerCase();
        freeWord = freeWord.replace(" △ ", " and ");
        freeWord = freeWord.replace(" ▽ ", " or ");
        freeWord = freeWord.replace(" ⊿◤ ", " not ");
        freeWord = freeWord.replace("卍", "(").replace("卐", ")");

        freeWord = freeWord.replaceAll(" #z#a#f#n#fd# ", " & ");
        freeWord = freeWord.replace("<zfl>yu<zfl>", "&amp;");
        freeWord = freeWord.replace("<zfl>huo<zfl>", "|");
        freeWord = freeWord.replace("<zfl>fei<zfl>", "~");

        zsout("初步拆分的单个条件___" + freeWord, "绿色", printLog);


        BoolQuery.Builder boolQueryBuilder = new BoolQuery.Builder();


        Pattern pattern = Pattern.compile(".*\\[([a-zA-Z]+)\\]");
        Matcher matcher = pattern.matcher(freeWord);

        /**
         * 有限定词
         */
        if (matcher.find()) {
            String xian_ding = matcher.group(1);
            String search_world = freeWord.replace("[" + xian_ding + "]", "").trim();

            if (xian_ding.equals("encnti")) {
                xian_ding = "ti";
            }
            if (xian_ding.equals("title")) {
                xian_ding = "ti";
            }
            if (xian_ding.equals("abstract")) {
                xian_ding = "ab";
            }
            if (xian_ding.equals("py")) {
                xian_ding = "year";
            }
            if (xian_ding.equals("ta")) {
                xian_ding = "journal";
            }
            if (xian_ding.equals("kw") || xian_ding.equals("keyword")) {
                xian_ding = "key_word_list";
            }
            if (xian_ding.equals("au") || xian_ding.equals("ahthor")) {
                xian_ding = "auth";
            }
            if (xian_ding.equals("mesh")) {
                search_world = search_world.replaceAll("\\*", "").trim();
            }
            zsout("实际使用的检索词___" + search_world, printLog);
            zsout("实际使用的限定词___" + "[" + xian_ding + "]", printLog);


            if (enCnSet().contains("[" + xian_ding + "]")) {
                /**
                 * 双份限定词的严格匹配
                 */
                if (search_world.startsWith("\"") && search_world.endsWith("\"")) {
                    search_world = search_world.substring(0, search_world.length() - 1);
                    search_world = search_world.substring(1);
                    if (xian_ding.equals("ti")) {//如果是标题
                        boolQueryBuilder.must(EN_CN_Term_query.en_cn_term_query(search_world, "cn_ti", "title", printLog));
                    } else if (xian_ding.equals("ab")) {//中英文摘要
                        boolQueryBuilder.must(EN_CN_Term_query.en_cn_term_query(search_world, "cn_ab", "ab", printLog));
                    } else if (xian_ding.equals("background")) {//中英文摘要
                        boolQueryBuilder.must(EN_CN_Term_query.en_cn_term_query(search_world, "cn_background", "background", printLog));
                    } else if (xian_ding.equals("methods")) {//中英文摘要
                        boolQueryBuilder.must(EN_CN_Term_query.en_cn_term_query(search_world, "cn_methods", "methods", printLog));
                    } else if (xian_ding.equals("results")) {//中英文摘要
                        boolQueryBuilder.must(EN_CN_Term_query.en_cn_term_query(search_world, "cn_results", "results", printLog));
                    } else if (xian_ding.equals("conclusion")) {//中英文摘要CONCLUSION
                        boolQueryBuilder.must(EN_CN_Term_query.en_cn_term_query(search_world, "cn_discussion", "discussion", printLog));
                    }
                } else {
                    /**
                     * 双份限定词的模糊匹配
                     */
                    String searchWorld = search_world;
                    if (xian_ding.equals("ti") || xian_ding.equals("title")) {//如果是标题
                        boolQueryBuilder.must(EN_CN_Match_query.en_cn_match_query(searchWorld, "cn_ti", "title", printLog));
                    } else if (xian_ding.equals("abstract") || xian_ding.equals("ab")) {//中英文摘要
                        boolQueryBuilder.must(EN_CN_Match_query.en_cn_match_query(searchWorld, "cn_ab", "ab", printLog));
                    } else if (xian_ding.equals("background")) {//背景
                        boolQueryBuilder.must(EN_CN_Match_query.en_cn_match_query(searchWorld, "cn_background", "background", printLog));
                    } else if (xian_ding.equals("methods")) {//方法
                        boolQueryBuilder.must(EN_CN_Match_query.en_cn_match_query(searchWorld, "cn_methods", "methods", printLog));
                    } else if (xian_ding.equals("results")) {//结果
                        boolQueryBuilder.must(EN_CN_Match_query.en_cn_match_query(searchWorld, "cn_results", "results", printLog));
                    } else if (xian_ding.equals("conclusion")) {//结论
                        boolQueryBuilder.must(EN_CN_Match_query.en_cn_match_query(searchWorld, "cn_discussion", "discussion", printLog));
                    }
                }
            }
            /**
             * 如果是单限定词
             */
            else if (ownSet().contains("[" + xian_ding + "]")) {
                if (search_world.startsWith("\"") && search_world.endsWith("\"")) {
                    if (xian_ding.equals("ts")) {
                        boolQueryBuilder.must(Ts_Term_query.ts_trem_query(search_world, printLog));
                    } else {
                        search_world = search_world.substring(0, search_world.length() - 1);
                        search_world = search_world.substring(1);
                        boolQueryBuilder.must(One_Field_Term_query.one_field_term_query(xian_ding, search_world, printLog));
                    }
                } else {
                    /**
                     * 普通限定词 没有引号 也没有星号
                     */
                    if (xian_ding.equals("doi")) {//如果是DOI
                        search_world = search_world.toLowerCase().replace("doi:", "").trim();
                        String finalPrefix = search_world;
                        BoolQuery.Builder oneQuery = new BoolQuery.Builder();
                        oneQuery.should(TermQuery.of(i -> i.field("doi.keyword").value(finalPrefix))._toQuery());
                        boolQueryBuilder.must(oneQuery.build()._toQuery());
                    } else if (xian_ding.equals("auth")) {//如果是作者
                        String finalPrefix1 = search_world;
                        boolQueryBuilder.must(TermQuery.of(i -> i.field("auth.keyword").value(finalPrefix1.toLowerCase()))._toQuery());
                    } else if (xian_ding.equals("unit")) {//如果是单位的筛选
                        try {
                            String unitValue = search_world;
                            if (search_world.contains("-")) {
                                TermQuery query = TermQuery.of(i -> i.field("cn_unit.keyword").value(k -> k.stringValue(unitValue)));
                                boolQueryBuilder.must(query._toQuery());
                            } else {
                                Query queryMatch = MatchQuery.of(i -> i.field("cn_unit").query(unitValue))._toQuery();
                                boolQueryBuilder.must(queryMatch);
                            }
                        } catch (Exception e) {
                            e.printStackTrace(System.err);
                        }
                    } else if (xian_ding.equals("ad")) {//这里的AD字段是只用于了WOS检索
                        boolQueryBuilder.must(One_Field_Match_query.one_field_match_query("pm_ad", search_world, printLog));

                    } else if (xian_ding.equals("ts")) {//如果是主题检索
                        boolQueryBuilder.must(Ts_match_query.ts_match_query(search_world, printLog));
                    } else if (xian_ding.equals("nsfcunit")) {//如果是单位的筛选
                        try {
                            String finalPrefix15 = search_world;
                            Query queryMatch = MatchQuery.of(i -> i.field("unit").query(finalPrefix15))._toQuery();
                            boolQueryBuilder.must(queryMatch);
                        } catch (Exception e) {
                            e.printStackTrace(System.err);
                        }
                    } else {
                        boolQueryBuilder.must(One_Field_Match_query.one_field_match_query(xian_ding, search_world, printLog));

                    }
                }
            }
        } else {
            /**
             * 没有限定词的严格匹配
             */
            if (freeWord.startsWith("\"") && freeWord.endsWith("\"")) {
                boolQueryBuilder.must(All_Field_Term_query.all_field_term_query(freeWord, printLog));//第三种
            } else {
                boolQueryBuilder.must(All_Field_Match_query.all_field_match_query(freeWord, printLog));
            }
        }
        return boolQueryBuilder.build()._toQuery();
    }

    public Set<String> enCnSet() {
        Set<String> set = new HashSet<>();
        set.add("[ti]");
        set.add("[ab]");

        set.add("[background]");
        set.add("[methods]");
        set.add("[results]");
        set.add("[conclusion]");

        return set;
    }

    //只走自己的检索
    public Set<String> ownSet() {
        Set<String> set = new HashSet<>();

        set.add("[ts]");

        set.add("[mesh]");

        set.add("[au]");
        set.add("[auth]");
        set.add("[author]");

        set.add("[key_word_list]");
        set.add("[pmid]");
        set.add("[doi]");

        set.add("[drug]");
        set.add("[gene]");
        set.add("[pathway]");
        set.add("[disease]");

        set.add("[ta]");
        set.add("[jour]");
        set.add("[journal]");

        set.add("[au]");

        set.add("[unit]");
        set.add("[nsfcunit]");
        set.add("[ta]");

        set.add("[year]");

        set.add("[ad]");
        set.add("[doi]");
        //[BACKGROUND]   [METHODS]  [RESULTS] [CONCLUSION]
        return set;
    }
}
